from pms.common.views import PostFormula, PermissionDeny
from info.utils.mail.sender import update_mail
from info.utils.mail import mail_view
from info.models import Mail
from department.utils import assert_department_permissions
from department.utils.member import assert_member_of as assert_department_member_of
from project.utils.member import assert_member_of as assert_project_member_of
from project.utils.permission import assert_project_permissions
from user.utils.permission import assert_system_permissions


class API(PostFormula):
    def handle(self, req):
        mail = Mail.objects.get(id=req['id'])
        if self.user != mail.uid:
            raise PermissionDeny
        if mail.did is not None:
            assert_department_member_of(self.user, mail.did)
            assert_department_permissions(self.user.id, mail.did.id, [4])
        elif mail.pid is not None:
            assert_project_member_of(self.user, mail.pid)
            assert_project_permissions(mail.pid.id, self.user.id, [6])
        else:
            assert_system_permissions(self.user.id, [15])
        return self.success_respond(
            mail_view(
                update_mail(mail, req['mod'])
            )
        )
